<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'vke:studentUser:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #userRoleString>
        <BasicTable @register="registerUserRoleTable" />
      </template>
      <template #userParentList>
        <BasicTable @register="registerUserParentTable" />
        <a-button class="mt-2" @click="handleParentsOfficeAdd">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>

    <!-- 头像上传 -->
    <!-- <CropperAvatar
      style="margin-left: 140px;"
      :value="avatar"
      btnText="更换头像"
      :btnProps="{ preIcon: 'ant-design:cloud-upload-outlined' }"
      @upload-success="aaa"
      @change="updateAvatar"
      width="150"
    /> -->
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsVkeStudentUserForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { CropperAvatar } from '/@/components/Cropper';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { uploadAvatar } from '/@/api/sys/upload';
  import {
    StudentUser,
    checkEmpNo,
    studentUserSave,
    studentUserForm,
  } from '/@/api/vke/studentUser';
  import { checkLoginCode } from '/@/api/sys/user';

  import { roleTreeData } from '/@/api/sys/role';
  import { BasicTable, useTable } from '/@/components/Table';
  // import { CropperAvatar } from '/@/components/Cropper';
  // import { Button, Row, Col } from 'ant-design-vue';
  // const avatarBase64 = ref<String>('');
  // const userStore = useUserStore();
  // const ARow = Row;
  // const ACol = Col;
  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('vke.studentUser');
  const { showMessage } = useMessage();
  const record = ref<StudentUser>({} as StudentUser);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增学生') : t('编辑学生'),
  }));
  const ctrlPermi = ref<String>('');
  const op = ref<String>('');
  const avatar = ref('');

  const inputFormSchemas: FormSchema[] = [
    // {
    //   label: t('基本信息'),
    //   field: 'employeeInfo',
    //   component: 'FormGroup',
    //   colProps: { lg: 24, md: 24 },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },
    {
      label: t('登录账号'),
      field: 'loginCode',
      component: 'Input',
      componentProps: {
        maxlength: 20,
      },
      rules: [
        { required: true },
        { min: 4, max: 20, message: t('请输入长度在 4 到 20 个字符之间') },
        { pattern: /^[\u0391-\uFFE5\w]+$/, message: t('不能输入特殊字符') },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              if (!value || value === '') return resolve();
              checkLoginCode(record.value.loginCode || '', value)
                .then((res) => (res ? resolve() : reject(t('登录账号已存在'))))
                .catch((err) => reject(err.message || t('验证失败')));
            });
          },
        },
      ],
    },
    {
      label: t('用户昵称'),
      field: 'userName',
      component: 'Input',
      componentProps: {
        maxlength: 32,
      },
      required: true,
    },
    {
      label: t('学号'),
      field: 'vstudent.studentNumber',
      component: 'Input',
      componentProps: {
        maxlength: 32,
      },
      required: true,
    },
    {
      label: t('姓名'),
      field: 'vstudent.studentName',
      component: 'Input',
      componentProps: {
        maxlength: 300,
      },
      required: true,
      // ifShow: () => op.value === 'add' || op.value === 'edit',
      // rules: [{ type: 'email', message: t('请填写正确的邮箱地址') }],
    },
    {
      label: t('学籍状态'),
      field: 'vstudent.studentStatus',
      component: 'Select',
      componentProps: {
        dictType: 'vke_student_status',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    // {
    //   label: t('办公电话'),
    //   field: 'phone',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 100,
    //   },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },
    // {
    //   label: t('权重'),
    //   field: 'userWeight',
    //   helpMessage: '排序，权重越大排名越靠前，请填写数字。',
    //   component: 'InputNumber',
    //   defaultValue: 0,
    //   componentProps: {
    //     maxlength: 8,
    //   },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },

    {
      label: t('详细信息'),
      field: 'employeeInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },

    // {
    //   label: t('员工工号'),
    //   field: 'employee.empNo',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 32,
    //   },
    //   rules: [
    //     { required: false },
    //     {
    //       validator(_rule, value) {
    //         return new Promise((resolve, reject) => {
    //           if (!value || value === '') return resolve();
    //           checkEmpNo(record.value.employee?.empNo || '', value)
    //             .then((res) => (res ? resolve() : reject(t('员工工号已存在'))))
    //             .catch((err) => reject(err.message || t('验证失败')));
    //         });
    //       },
    //     },
    //   ],
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },
    {
      label: t('出生年月'),
      field: 'vstudent.dateBirth',
      component: 'DatePicker',
      componentProps: {
        dictType: 'sys_user_sex',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('性别'),
      field: 'vstudent.sex',
      component: 'RadioGroup',
      // defaultValue: '1',
      componentProps: {
        dictType: 'sys_user_sex',
        allowClear: true,
      },
      required: true,
      // ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    // {
    //   label: t('用户类型'),
    //   field: 'userType',
    //   component: 'Select',
    //   componentProps: {
    //     dictType: 'sys_user_type',
    //     allowClear: true,
    //   },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },
    {
      label: t('年级'),
      field: 'vstudent.grade',
      component: 'Select',
      componentProps: {
        dictType: '	vke_grade',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('班级'),
      field: 'vstudent.classCode',
      component: 'Select',
      componentProps: {
        dictType: '	vke_class',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('身份证号'),
      field: 'vstudent.identityCard',
      component: 'Input',
      componentProps: {
        maxlength: 32,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('头像'),
      field: 'vstudent.headPortrait',
      component: 'Uploads',
      componentProps: {
        multiple: false,
        maxNumber: 1,
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'teacherUser_avatar',
        uploadType: 'image',
        onChange: (e: ChangeEvent) => {
          console.log(e);
          avatar.value = e;
        },
      },
      ifShow: () => {
        return op.value === 'add' || op.value === 'edit';
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('家长'),
      field: 'vstudent.parentList',
      component: 'Input',
      slot: 'userParentList',
      colProps: { lg: 24, md: 24 },
    },
    // {
    //   label: t('家长电话'),
    //   field: 'vstudent.parentPhone',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 32,
    //   },
    //   required: true,
    // },
    // {
    //   label: t('紧急联系电话'),
    //   field: 'vstudent.urgentPhone',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 32,
    //   },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },
    // {
    //   label: t('头像'),
    //   field: 'vstudent.headPortrait',
    //   component: 'Upload',
    //   componentProps: {
    //     // loadTime: computed(() => record.value.__t),
    //     // bizKey: computed(() => record.value.id),
    //     bizType: 'testData_image',
    //     uploadType: 'image',
    //   },
    //   colProps: { lg: 24, md: 24 },
    // },
    // {
    //   label: t('头像'),
    //   field: 'vstudent.urgentPhone',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 32,
    //   },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },
    // {
    //   label: t('备注信息'),
    //   field: 'remarks',
    //   component: 'InputTextArea',
    //   componentProps: {
    //     maxlength: 500,
    //   },
    //   colProps: { lg: 24, md: 24 },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },

    {
      label: t('角色信息'),
      field: 'roleInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: () => op.value === 'add' || op.value === 'auth',
    },
    {
      label: t('分配角色'),
      field: 'userRoleString',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'userRoleString',
      show: () => op.value === 'add' || op.value === 'auth',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
    labelWidth: 120,
  });

  // async function getEmployeeOfficeList() {
  //   let employeeOfficeListValid = true;
  //   let employeeOfficeList = employeeOfficeTable.getDataSource();
  //   for (const record of employeeOfficeList) {
  //     if (!(await record.onEdit?.(false, true))) {
  //       employeeOfficeListValid = false;
  //     }
  //   }
  //   if (!employeeOfficeListValid) {
  //     throw new Error('employeeOfficeList valid.');
  //   }
  //   return employeeOfficeList;
  // }

  const [registerUserRoleTable, userRoleTable] = useTable({
    columns: [
      {
        title: t('角色名称'),
        dataIndex: 'name',
        width: 260,
        align: 'center',
      },
      {
        title: t('角色编码'),
        dataIndex: 'id',
        width: 260,
        align: 'center',
      },
    ],
    rowSelection: { type: 'checkbox' },
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  const [registerUserParentTable, userParentTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleDelete.bind(this, record),
          },
          auth: 'sys:empUser:edit',
        },
      ],
    },
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  const base64ConvertFile = function (urlData) {
    // 64转file
    if (typeof urlData != 'string') {
      // $toast("urlData不是字符串")
      return;
    }
    var arr = urlData.split(',');
    var type = arr[0].match(/:(.*?);/)[1];
    var fileExt = type.split('/')[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], 'filename.' + fileExt, {
      type: type,
    });
  };
  async function updateAvatar(option) {
    let res = base64ConvertFile(option);
    console.log(res);
    let result = await uploadAvatar({ file: res, bizKey: 'student01_s6jm',bizType:'studentUser_avatar',fileName: 'avatar (1).png' });
    console.log(result);
  }

  async function setUserRoleTableData(res: Recordable) {
    const dataSource = await roleTreeData({
      userType: 'student',
      ctrlPermi: ctrlPermi.value,
    });
    userRoleTable.setTableData(dataSource || []);
    userRoleTable.setSelectedRowKeys(res.roleList?.map((item) => item.id) || []);
  }
  function setUserParentTableData(res: Recordable) {
    userParentTable.setColumns([
      {
        title: t('家长类型'),
        dataIndex: 'relationName',
        width: 260,
        align: 'center',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 's_index_parents',
          onChange: (e) => {
            console.log(e);
          },
        },
        editRule: true,
        slots: { customRender: 'userRole' },
      },
      {
        title: t('电话'),
        dataIndex: 'relationPhone',
        width: 260,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
    ]);
    if (res.studentUser.vstudent.parentList) {
      userParentTable.setTableData(res.studentUser.vstudent.parentList);
    } else {
      userParentTable.setTableData([]);
    }
    // userRoleTable.setSelectedRowKeys(res.roleList?.map((item) => item.id) || []);
  }
  function handleParentsOfficeAdd() {
    userParentTable.insertTableDataRecord({
      id: 'rid_' + new Date().getTime(),
      editable: true,
    });
  }
  function handleDelete(record: Recordable) {
    userParentTable.deleteTableDataRecord(record);
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    userRoleTable.setTableData([]);
    userRoleTable.setSelectedRowKeys([]);
    setDrawerProps({ loading: true });
    op.value = data.op || 'add';
    const res = await studentUserForm(data);
    record.value = (res.studentUser || {}) as StudentUser;
    ctrlPermi.value = res.ctrlPermi || '2';
    setFieldsValue(record.value);
    updateSchema([
      {
        field: 'loginCode',
        componentProps: {
          disabled: op.value === 'auth',
        },
      },
      {
        field: 'userName',
        componentProps: {
          disabled: op.value === 'auth',
        },
      },
    ]);
    if (op.value === 'add' || op.value === 'edit') {
      setUserParentTableData(res);
    }
    if (op.value === 'add' || op.value === 'auth') {
      setUserRoleTableData(res);
    }
    setDrawerProps({ loading: false });
  });
  async function getuserRoleTableList() {
    let employeeOfficeListValid = true;
    let userRoleTableList = userParentTable.getDataSource();
    for (const record of userRoleTableList) {
      if (!(await record.onEdit?.(false, true))) {
        employeeOfficeListValid = false;
      }
    }
    if (!employeeOfficeListValid) {
      throw new Error('userRoleTableList valid.');
    }
    return userRoleTableList;
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      console.log(data);
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        userCode: record.value.userCode,
        op: op.value,
      };

      data.userType = 'student';
      // if (op.value === 'add' || op.value === 'edit') {
      //   if (!data.employee.empNo) {
      //     data.employee.empNo = record.value.loginCode;
      //   }
      //   // console.log(getEmployeeOfficeList(),6666666);
      //   // data.employee.employeeOfficeList = await getEmployeeOfficeList();
      // }
      if (op.value === 'add' || op.value === 'auth') {
        data.userRoleString = userRoleTable.getSelectRowKeys().join(',');
      }
      if (op.value === 'add' || op.value == 'edit') {
        data.studentUser_avatar = avatar.value.id;
        data.vstudent.headPortrait = avatar.value.fileUrl;
        // data.headPortrait = avatar.fileEntity.fileMd5
        data.user = record.value.userCode;
        data.vstudent.studentId = record.value.vstudent.studentId;
        // data.studentId
        let parent = await getuserRoleTableList();
        let parentInfo = [];
        parent.forEach((item,index) => {
          console.log(item.relationName, item.relationCode);
          let info;
          if (item.relationCode) {
            info = {
              relationName: item.relationName,
              // relationId: item.relationId,
              relationPhone: item.relationPhone,
              relationCode: item.relationCode,
              studentId: record.value.userCode,
            };
          } else {
            info = {
              // relationId: item.relationId,
              relationPhone: item.relationPhone,
              relationCode: item.relationName,
              studentId: record.value.userCode,
            };
          }
          parentInfo.push(info);
          //   if (numRe.test(item.name)) {
          //     item.relationCode = item.name;
          //     console.log(item);
          //     delete item.name;
          //   }
        });
        console.log(parentInfo);
        if (parentInfo.length > 0) {
          data.vstudent.parentInfo = JSON.stringify(parentInfo);
        } else {
          data.vstudent.parentInfo = '';
        }
        if (data.vstudent.parentList) {
          delete data.vstudent.parentList;
        }
      }
      console.log(data);
      const res = await studentUserSave(params, data);
      // console.log(res,'報錯');
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  .change-avatar {
    img {
      display: block;
      margin-bottom: 15px;
      border-radius: 50%;
    }
  }
</style>
